package com.example.prison.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.prison.config.FileUtil;
import com.example.prison.config.Response;
import com.example.prison.entity.CarManagement;
import com.example.prison.entity.PeopleManage;
import com.example.prison.service.CarManagementService;
import com.example.prison.service.PeopleManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Api(tags = "B导入导出管理")
@RestController
@RequestMapping("/api")
public class InputController {

    @Autowired
    private PeopleManageService personnelManagementService;

    @Autowired
    private CarManagementService carManagementService;

//    @Autowired
//    private SystemLogService systemLogService;

    @PostMapping("/inputPersonnelExcel")
    @ApiOperation("导入人员")
    public Response<?> inputPersonnelExcel(@RequestPart MultipartFile file) {
        if (file == null || file.getSize() == 0) {
            return Response.error("文件为空，导入失败！");
        }
        List<String> list = new ArrayList<>();
        try {
            ImportParams params = new ImportParams();
            List<PeopleManage> cardList = ExcelImportUtil.importExcel(FileUtil.convertFile(file),PeopleManage.class,params);
            System.out.println(cardList);
            if (ObjectUtils.isEmpty(cardList)) {
                return Response.info("文件数据为空！");
            }
            for (PeopleManage card : cardList) {
                if(ObjectUtils.isNotEmpty(personnelManagementService.getOnePersonnelByIDCard(card.getIdCard()))) {
                    list.add(card.getIdCard());
                }
            }
            if (list.size() > 0) {
                return Response.error("文件导入失败！重复的身份证号码数据:"+ list);
            } else {
                for (PeopleManage card : cardList) {
                    personnelManagementService.add(card);
                }
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
            return Response.error("文件导入失败！"+e);
        }
        log.info("导入人员");
//        systemLogService.addLog("导入人员");
        return Response.success("文件导入成功！");
    }

    @PostMapping("/inputCarExcel")
    @ApiOperation("导入车辆")
    public Response<?> inputCarExcel(@RequestPart MultipartFile file) {
        List<String> list = new ArrayList<>();
        try {
            ImportParams params = new ImportParams();
            List<CarManagement> cardList = ExcelImportUtil.importExcel(FileUtil.convertFile(file),CarManagement.class,params);
            if (ObjectUtils.isEmpty(cardList)) {
                return Response.info("文件数据为空！");
            }
            for (CarManagement card : cardList) {
                if(ObjectUtils.isNotEmpty(carManagementService.getOneByNumber(card.getCarNumber()))) {
                    list.add(card.getCarNumber());
                }
            }
            if (list.size() > 0) {
                return Response.error("文件导入失败！重复的车牌号数据:"+list);
            } else {
                for (CarManagement card : cardList) {
                    carManagementService.add(card);
                }
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
            return Response.error("文件导入失败！");
        }
        log.info("导入车辆");
//        systemLogService.addLog("导入车辆");
        return Response.success("文件导入成功！");
    }

    @PostMapping("/exportToPersonneExcel")
    @ApiOperation("导出人员模板")
    public void exportToPersonneExcel(@Parameter(description = "导出路径",required = true)String filePath) throws IOException {
        com.example.prison.util.FileUtil.DeleteTxtFile(filePath);
        List<PeopleManage> persons = personnelManagementService.list();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Persons");

        // Create header row
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("姓名");
        headerRow.createCell(1).setCellValue("性别");
        headerRow.createCell(2).setCellValue("部门");
        headerRow.createCell(3).setCellValue("职位");
        headerRow.createCell(4).setCellValue("人员状态");
        headerRow.createCell(5).setCellValue("籍贯");
        headerRow.createCell(6).setCellValue("民族");
        headerRow.createCell(7).setCellValue("联系方式");
        headerRow.createCell(8).setCellValue("家庭地址");
        headerRow.createCell(9).setCellValue("身份证号码");

        // Fill data
        int rowNum = 1;
        for (PeopleManage person : persons) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(person.getName());
            row.createCell(1).setCellValue(person.getGender());
            row.createCell(2).setCellValue(person.getUnit());
            row.createCell(3).setCellValue(person.getPost());
            row.createCell(4).setCellValue(person.getStatus());
            row.createCell(5).setCellValue(person.getNativePlace());
            row.createCell(6).setCellValue(person.getNationality());
            row.createCell(7).setCellValue(person.getPhone());
            row.createCell(8).setCellValue(person.getAddress());
            row.createCell(9).setCellValue(person.getIdCard());
        }

        // Write the output to a file
        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        }

        // Closing the workbook
        workbook.close();
    }

    @PostMapping("/exportToCarExcel")
    @ApiOperation("导出车辆模板")
    public void exportToCarExcel(@Parameter(description = "导出路径",required = true)String filePath) throws IOException {
        com.example.prison.util.FileUtil.DeleteTxtFile(filePath);
        List<CarManagement> persons = carManagementService.list();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Car");

        // Create header row
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("车牌号");
        headerRow.createCell(1).setCellValue("所属部门");
        headerRow.createCell(2).setCellValue("车辆状态");

        // Fill data
        int rowNum = 1;
        for (CarManagement person : persons) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(person.getCarNumber());
            row.createCell(1).setCellValue(person.getCarDepart());
            row.createCell(2).setCellValue(person.getCarStatus());
        }

        // Write the output to a file
        try (FileOutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        }

        // Closing the workbook
        workbook.close();
    }

}
